package com.soft.line.service.impl;


import com.github.pagehelper.PageInfo;
import com.soft.line.entity.UserInfo;
import com.soft.line.filter.HttpRequestUtil;
import com.soft.line.filter.UserTokenDto;
import com.soft.line.mapper.UserInfoMapper;
import com.soft.line.service.UserInfoService;
import com.soft.line.util.pagehelper.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author wu.xueqiao on 2020/5/12.
 * @version 0.1
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;


    @Override
    public UserInfo getUserInfo(int userId) {
        return userInfoMapper.selectByPrimaryKey(userId);
    }

    @Override
    public PageInfo<UserInfo> getAllUsers(Map<String, Object> map) {
        PageUtil.setPageParam(map);
        List<UserInfo> userInfos=userInfoMapper.getAllUsers(map);
        PageInfo<UserInfo> beans = new PageInfo(userInfos);
        beans.setList(userInfos);
        return beans;
    }

    @Override
    public int delUser(int id) {
        int result=userInfoMapper.delUser(id);
        if(result==1){
            return 1;
        }else {
            return 0;
        }
    }

    @Override
    public int addUser(UserInfo userInfo) {
        UserTokenDto userTokenDto= HttpRequestUtil.getUserToken();
        userInfo.setModifyPerson(userTokenDto.getUserInfo().getUserName());
        if (userInfo.getId()==null){
            return userInfoMapper.insert(userInfo);
        }else {
            return  userInfoMapper.updateUserInfo(userInfo);
        }

    }

    @Override
    public Boolean changePassword(Map<String, Object> map) {
        int id=Integer.valueOf(map.get("id").toString());
        UserInfo userInfo=userInfoMapper.selectByPrimaryKey(id);
        String password=userInfo.getPassword();
        String oldPassword=map.get("oldPassword").toString();
        String newPassword=map.get("newPassword").toString();
        String confirmPassword=map.get("confirmPassword").toString();
        if(password.equals(oldPassword) && newPassword.equals(confirmPassword)){
            userInfo.setPassword(newPassword);
            int update=userInfoMapper.updateUserInfo(userInfo);
            if(update==1){
                return true;
            }
        }
        return false;
    }

    @Override
    public int countByRoleId(Integer roleId) {
        return userInfoMapper.countByRoleId(roleId);
    }
}
